package com.etlmaster.executor.steps.load;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

import com.etlmaster.core.DataSourceDefine;
import com.etlmaster.core.DataSourceHolder;
import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.steps.extract.ExtractUtil;
import com.etlmaster.executor.utils.DataCollectionUtils;
import com.etlmaster.executor.utils.StepState;


/**
 * @author Lizq
 * @date 2016-07-1
 */
@StepInstruction("gbaseImport")

public class GbaseImportStep extends Step {
	
	private GbaseImportStepMeta meta;
	private final static String gbase_default_port="5258";
	public GbaseImportStep(StepMeta meta) {
		super(meta);
		this.meta=(GbaseImportStepMeta) meta;
	}

	@Override
	protected int handle() {
		int flag = StepState.RUNNING_SUCCESSED;
		String exportSql=DataCollectionUtils.getProperties("gbase_importCmd");
		String gbaseHome=DataCollectionUtils.getProperties("gbaseHome");
		if(StringUtils.isEmpty(gbaseHome)){
			meta.log("ERROR", "找不到gbaseHome配置");
			flag=StepState.RUNNING_FAILED;
			return flag;
		}
		if(StringUtils.isEmpty(exportSql)){
			meta.log("ERROR", "找不到gbase_importCmd配置");
			flag=StepState.RUNNING_FAILED;
			return flag;
		}
		Map<String,Object> map=ExtractUtil.getMap(meta);
		
		/*JdbcTemplate jdbc=new JdbcTemplate();
		String fetchUserInfo="select url ,username,password from metadbcfg where dbname='"+meta.getDsName()+"'";
		Map<String, Object> dbInfo=jdbc.queryForMap(fetchUserInfo);
		
		String password=DesCipher.decrypt(dbInfo.get("password").toString());
		String port=getPort(dbInfo.get("url").toString());
		String username=dbInfo.get("username").toString();
		*/
		DataSourceDefine def=DataSourceHolder.getInstance().getDataSourceDefine(meta.getDsName());
		String password=def.getPassword();
		String port=getPort(def.getUrl());
		String username=def.getUsername();
		
		if(StringUtils.isEmpty(port)){
			port=gbase_default_port;
			meta.log("WARN", "找不到数据库连接端口，采用默认端口：[{}]",gbase_default_port);
		}
		
		map.put("userName",username);
		map.put("passWord", password);
		map.put("serverPort", port);
		String cmd=gbaseHome+exportSql;
		cmd=ExtractUtil.replace(cmd, map);
		flag=ExtractUtil.execute(cmd);
		return flag;
	}
	private String getPort(String url){
		String regex="//(.*?):(\\d+)";
		Pattern p=Pattern.compile(regex);
		Matcher m=p.matcher(url);
		if(m.find()){
			return m.group(2);
		}else{
			return "";
		}
	}

	@Override
	public boolean stop() {
		// TODO Auto-generated method stub
		return false;
	}
	

}
